<?php
/**
 * 全局函数
 *
 * @author 孙晓晔
 * @version $Id: function.php 996 2010-03-11 07:05:26Z sunxy $
 */

/**
 * 连接MySQL数据库
 *
 * @param string $conn
 * @return mysql $db
 */
function &newdb($conn) {
	global $cfg;

	// echo 'db1 = ' . $conn . "\n";

	$aa = explode('.', $conn);
	if (count($aa) > 1) {
		$conn = $aa[0];
	}

	// echo 'db2 = ' . $conn . "\n";

	$h = $cfg['mysql'][$conn];

	$db = new MySQL;
	$db->connect($h["host"], $h["user"], $h["pass"]);

	if (!$db->dbh) {
		$h = $cfg['mysql']["root"];
		$db->connect($h["host"], $h["user"], $h["pass"]);
	}

	$db->select_db($h["db"]);
	$db->query("set names 'utf8'");
	return $db;
}

/**
 * 连接PostgreSQL数据库
 *
 * @param string $conn
 * @return mysql $db
 */
function &newpg($conn) {
	global $cfg;

	$h = $cfg['pgsql'][$conn];

	$db = new PGM_Sql();
	$db->connect($h["host"], $h["db"], $h["user"], $h["pass"]);

	return $db;
}

/**
 * 连接FTP站点
 *
 * @param string $conn
 * @return FTP $conn_id
 */
function &newftp($conn) {
	global $cfg;

	$t = $cfg['ftp'][$conn];
	$conn_id = ftp_connect($t['host'], $t['port'], 10) or die("Couldn't connect to " . $t['host']);
	ftp_login($conn_id, $t['user'], $t['pass']);
	ftp_chdir($conn_id, $t['dir']);
	ftp_pasv($conn_id, true);

	return $conn_id;
}

function &newfs($conn) {
	if (!class_exists("MogileFs")) {
		return false;
	}

	global $cfg;

	$t = $cfg['mogilefs'][$conn];

	$mg = new MogileFs();
	$mg->connect($t['host'], $t['port'], $t['domain']);

	return $mg;
}

function astman($conn) {
	global $cfg;

	require_once APP_LIB . DIRECTORY_SEPARATOR . 'phpagi-asmanager.php';

	$t = $cfg['asterisk'][$conn];

	$am = new AGI_AsteriskManager(NULL, $t);
	$am->connect();

	return $am;
}

function memcache($conn) {
	global $cfg;

	$t = $cfg['memcached'][$conn];
	$mc = new Memcache();
	if ($mc->connect($t['host'], $t['port'])) {
		return $mc;
	}

	return null;
}

function _strtotime($s) {
	$t = strtotime($s);

	return $t - time();
}

function clean($key) {
	$mc = memcache("root");
	if (is_object($mc)) {
		$mc->delete($key, 0);
	}
}

/**
 * 调试工具
 */
function debug($s, $file = null) {
	if (empty($s)) {
		return false;
	}

	global $cfg;

	if (isset($cfg['log_dir'])) {
		$d = $cfg['log_dir'];
	} else {
		$b = APP_ROOT . "/../../";
		$d = $b . "/../compile/";
		if (!file_exists($d)) {
			$d = $b . "/../";
		}
	}

	if ($file == null) {
		$file = date("Ym") . ".txt";
	}

	$fd = @fopen($d . $file, "a+");
	@fwrite($fd, date("Y-m-d H:i:s") . " ");
	if (isset($_SERVER["REMOTE_ADDR"])) {
		@fwrite($fd, $_SERVER["REMOTE_ADDR"] . " ");
	}

	if (isset($_SERVER["HTTP_HOST"])) {
		@fwrite($fd, "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"] . "?". $_SERVER["QUERY_STRING"] . " ");
	}

	@fwrite($fd, $s . "\n");
	@fclose($fd);
}

function paddslashes($data) {
	if(is_array($data) and !empty($data)) {
		foreach($data as $k=>$v) {
			$data[$k] = paddslashes($v);
		}
	} else{
		$data = addslashes($data);
	}
	return $data;
}

function pstripslashes($data) {
	if(is_array($data) and !empty($data)) {
		foreach($data as $k=>$v) {
			$data[$k] = pstripslashes($v);
		}
	} else{
		$data = stripslashes($data);
	}
	return $data;
}

/**
 * 判断数组值是否为空，$num为可以为空的个数
 *
 * @param aray $arr
 * @param intger $num
 * @return bool
 */
function isempty($arr, $num = 1) {
	if (!is_array($arr) && empty($arr)) {
		return true;
	}

	$i = 0;
	foreach($arr as $k => $v) {
		if (trim($v) == '') {
			$i++;
		}
	}
	if ($i > $num) {
		return true;
	}
	return false;
}

/**
 * 修正的除法，除数为0的默认返回0
 *
 * @param unknown_type $a
 * @param unknown_type $b
 */
function div($a, $b) {
	if ($b == 0) {

		return 0;
	}

	return round($a / $b, 2);
}

/**
 * 实体化HTML标签
 *
 * @param unknown_type $data
 * @return unknown
 */
function html($data) {
	if(is_array($data)) {
		foreach($data as $k => $v) {
			$data[$k] = html($v);
		}
	} else {
		$data = htmlentities($data, ENT_QUOTES, 'utf-8');
	}

	return $data;
}

function slashes($data) {
	if(is_array($data)) {
		foreach($data as $k => $v) {
			$data[$k] = slashes($v);
		}
	} else {
		$data = addslashes($data);
	}

	return $data;
}

function alert($msg) {
	echo "<script type='text/javascript'>alert(\"" . $msg .  "\")</script>";
}

/**
 * 计算字节数
 *
 * @param long $size
 * @return string 容量大小表达，如12.34MB
 */
function printsize($size) {
	$kb = 1024;
	$mb = 1024 * $kb;
	$gb = 1024 * $mb;

	if ($size > $gb) {
		$size = round($size / $gb, 2) . "GB";
	} elseif ($size > $mb) {
		$size = round($size / $mb, 2) . "MB";
	} elseif ($size > $kb) {
		$size = round($size / $kb, 2) . "KB";
	} else {
		$size .= "B";
	}

	return $size;
}

// UTF-8汉字转GBK汉字
function utf82gb($utfstr){
	if (function_exists('iconv')) {
		return iconv('utf-8','gbk',$utfstr);
	}

	global $UC2GBTABLE;
	$okstr = "";
	if (trim($utfstr) == "") {
		return $utfstr;
	}

	if (empty($UC2GBTABLE)) {
		$filename = APP_ROOT . '/../../inc/gb2312-utf8.table';
		$fp = fopen($filename,"r");
		while ($l = fgets($fp,15)) {
			$UC2GBTABLE[hexdec(substr($l, 7, 6))] = hexdec(substr($l, 0, 6));
		}
		fclose($fp);
	}

	$okstr = "";
	$ulen = strlen($utfstr);
	for ($i = 0; $i < $ulen; $i++) {
		$c = $utfstr[$i];
		$cb = decbin(ord($utfstr[$i]));
		if (strlen($cb) == 8) {
			$csize = strpos(decbin(ord($cb)),"0");
			for ($j = 0; $j < $csize; $j++){
				$i++;
				$c .= $utfstr[$i];
			}
				
			$c = utf82u($c);
			if (isset($UC2GBTABLE[$c])) {
				$c = dechex($UC2GBTABLE[$c]+0x8080);
				$okstr .= chr(hexdec($c[0].$c[1])).chr(hexdec($c[2].$c[3]));
			} else {
				$okstr .= "&#".$c.";";
			}
		} else {
			$okstr .= $c;
		}
	}
	$okstr = trim($okstr);
	return $okstr;
}

// GBK汉字转拼音
function SpGetPinyin($str, $ishead = 0, $isclose = 1){
	global $pinyins;
	$restr = "";
	$str = trim($str);
	$slen = strlen($str);
	if ($slen < 2) {
		return $str;
	}

	if (count($pinyins) == 0) {
		py_db(APP_ROOT . '/../../inc/pinyin.db');
		py_db(APP_ROOT . '/../../inc/pinyin.big5');
	}

	for ($i = 0; $i < $slen; $i++) {
		if (ord($str[$i]) > 0x80) {
			$c = $str[$i].$str[$i+1];
			$i++;
			if (isset($pinyins[$c])) {
				if ($ishead == 0) {
					$restr .= $pinyins[$c];
				} else {
					$restr .= $pinyins[$c][0];
				}
			} else {
				$restr .= "_";
			}
			// 		} else if (eregi("[a-z0-9]", $str[$i]) ) {
		} else if (preg_match("/[a-z0-9]/i", $str[$i]) ) {
			$restr .= $str[$i];
		} else {
			$restr .= "_";
		}
	}

	if ($isclose == 0) {
		unset($pinyins);
	}

	return $restr;
}

// UTF-8汉字转拼音
function getPinyin($string){
	return SpGetPinyin(utf82gb($string), 1);
}

function pinyins() {
	py_db(APP_ROOT . '/../../inc/pinyin.db');
	py_db(APP_ROOT . '/../../inc/pinyin.big5');
}

function py_db($file) {
	global $pinyins;

	$fp = fopen(APP_ROOT . '/../../inc/pinyin.db', "r");
	while(!feof($fp)){
		$line = trim(fgets($fp));
		$pinyins[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3);
	}

	fclose($fp);
}

function name_account($str) {
	global $pinyins;

	$str = trim($str);
	$slen = strlen($str);
	if ($slen < 2) {
		return $str;
	}

	if (count($pinyins) == 0) {
		py_db(APP_ROOT . '/../../inc/pinyin.db');
		py_db(APP_ROOT . '/../../inc/pinyin.big5');
	}

	$ret = "";
	for ($i = 0; $i < $slen; $i++) {
		$s = $str[$i];
		if (ord($s) > 0x80) {
			$c = $s . $str[$i+1];
			$i++;
			$b = $pinyins[$c];
			if (isset($b)) {
				if ($i == 1) {
					$ret .= $b;
				} else {
					$ret .= $b[0];
				}
			} else {
				$ret .= "_";
			}
		} else if (eregi("[a-z0-9]", $s) ) {
			$ret .= $s;
		} else {
			$ret .= "_";
		}
	}

	return $ret;
}

function str_py($str) {
	global $pinyins;

	$str = trim($str);
	$slen = strlen($str);
	if ($slen < 2) {
		return $str;
	}

	if (count($pinyins) == 0) {
		py_db(APP_ROOT . '/../../inc/pinyin.db');
		py_db(APP_ROOT . '/../../inc/pinyin.big5');
	}

	$ret = "";
	for ($i = 0; $i < $slen; $i++) {
		$s = $str[$i];
		if (ord($s) > 0x80) {
			$c = $s . $str[$i+1];
			$i++;
			$b = $pinyins[$c];
			if (isset($b)) {
				$ret .= _szmdx($b) . " ";
			} else {
				$ret .= "_";
			}
		} else if (eregi("[a-z0-9]", $s) ) {
			$ret .= $s;
		} else {
			$ret .= "_";
		}
	}

	return trim($ret);
}

function _szmdx($str) {
	if (empty($str)) {
		return '';
	}

	$a = strtoupper(substr($str, 0, 1));
	if (strlen($str) == 1) {
		return $a;
	}

	$ret = $a . substr($str, 1);

	return $ret;
}

function _emp($s) {
	// $f = _username($s);
	$tbl = Constant::tbl_emp;

	$db = newdb($tbl);
	if (preg_match("/^6\d{5}$/i", $s)) {
		$fmt = "SELECT * FROM %s WHERE status in ('1', '8') AND `short` = '%s'";
		$sql = sprintf($fmt, $tbl, $s);
	} else if (preg_match("/^1(3|4|5|8)\d{9}$/i", $s)) {

		$fmt = "SELECT * FROM %s WHERE status in ('1', '8') AND mobile = '%s'";
		$sql = sprintf($fmt, $tbl, $s);
	} else if (preg_match("/^\d+$/i", $s)) {
		$fmt = "SELECT * FROM %s WHERE status in ('1', '8') AND (id = '%s' OR exten = '%s')";
		$sql = sprintf($fmt, $tbl, $s, $s);
	} else {
		$fmt = "SELECT * FROM %s WHERE status in ('1', '8') AND name = '%s'";
		$sql = sprintf($fmt, $tbl, $s);
	}
	debug($sql);
	$result = $db->query($sql);
	if ($row = $db->fetch_array($result)) {
		return $row;
	}

	return false;
}

function _username($s) {
	if (preg_match("/^\d+$/i", $s)) {
		return _username_b($s);
	}

	return 'name';
}

function _username_b($s) {
	if (preg_match("/^(2|6|8)\d{3}$/i", $s)) {
		return 'exten';
	}

	if (preg_match("/^6\d{5}$/i", $s)) {
		return '`short`';
	}

	if (preg_match("/^1(3|4|5|8)\d{9}$/i", $s)) {
		return 'mobile';
	}

	return 'code';
}

function _password($password, $input) {
	$s = trim($input);
	if (strlen($s) == 0) {
		return false;
	}

	if ($password == $input) {
		return true;
	}

	if ($password == md5($input)) {
		return true;
	}

	return false;
}

function unicode_encode($name) {
	$name = iconv('UTF-8', 'UCS-2', $name);
	$len = strlen($name);
	$str = '';
	//for ($i = 0; $i < $len – 1; $i = $i + 2){
	for ($i = 0; $i < $len - 1; $i = $i + 2){
		$c = $name[$i];
		$c2 = $name[$i + 1];
		if (ord($c) > 0) {    // 两个字节的文字
			$str .= '\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
		} else {
			$str .= $c2;
		}
	}

	return $str;
}

function unicode_decode($name) {
	// 转换编码，将Unicode编码转换成可以浏览的utf-8编码
	$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
	preg_match_all($pattern, $name, $matches);
	if (!empty($matches)) {
		$name = '';
		for ($j = 0; $j < count($matches[0]); $j++) {
			$str = $matches[0][$j];
			if (strpos($str, '\\u') === 0) {
				$code = base_convert(substr($str, 2, 2), 16, 10);
				$code2 = base_convert(substr($str, 4), 16, 10);
				$c = chr($code).chr($code2);
				$c = iconv('UCS-2', 'UTF-8', $c);
				$name .= $c;
			} else {
				$name .= $str;
			}
		}
	}

	return $name;
}

function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
	static $recursive_counter = 0;
	if (++$recursive_counter > 1000) {
		die('possible deep recursion attack');
	}

	foreach ($array as $key => $value) {
		if (is_array($value)) {
			arrayRecursive($array[$key], $function, $apply_to_keys_also);
		} else {
			$array[$key] = $function($value);
		}

		if ($apply_to_keys_also && is_string($key)) {
			$new_key = $function($key);
			if ($new_key != $key) {
				$array[$new_key] = $array[$key];
				unset($array[$key]);
			}
		}
	}

	$recursive_counter--;
}

function quotes($content) {
	if (!get_magic_quotes_gpc()) {
		if (is_array($content)) {
			foreach ($content as $key=>$value){
				$content[$key] = quotes($value);
			}
		} else {
			addslashes($content);
		}
	}
	
	return $content;
}

function unquotes($content){
	if (get_magic_quotes_gpc()) {
		if (is_array($content)) {
			foreach ($content as $key=>$value) {
				$content[$key] = unquotes($value);
			}
		} else {
			stripslashes($content);
		}
	}
	
	return $content;
}
?>